package cn.wolfcode.web.exceptioncontrolleradvice;


import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.WebException;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {

    /**
     * 该方法是用于捕获并处理某种异常
     * e : 现在出现的异常对象
     * method : 现在出现异常的那个处理方法
     */
    @ExceptionHandler(WebException.class)
    public void webExceptionHandler(WebException e, HandlerMethod method, HttpServletResponse response) throws IOException {
        e.printStackTrace(); //方便开发的时候找bug
        //如果原本控制器的方法是返回jsonresult数据,现在出异常也应该返回jsonresult
        //获取当前出现异常的方法,判断是否有ResponseBody注解,有就代表需要返回jsonresult

        ResponseBody methodAnnotation = method.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation==null){
            response.sendRedirect("/error2");
        }else {
            response.setContentType("application/json;charset=utf-8");
            String jsonResult = JSON.toJSONString(new JsonResult(e.getMessage(), false));
            response.getWriter().write(jsonResult);
        }
    }

    @ExceptionHandler(Exception.class)
    public void exceptionHandler(RuntimeException e, HandlerMethod method, HttpServletResponse response) throws IOException {
        e.printStackTrace(); //方便开发的时候找bug
        //如果原本控制器的方法是返回jsonresult数据,现在出异常也应该返回jsonresult
        //获取当前出现异常的方法,判断是否有ResponseBody注解,有就代表需要返回jsonresult

        ResponseBody methodAnnotation = method.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation==null){
            response.sendRedirect("/error2");
        }else {
            response.setContentType("application/json;charset=utf-8");
            String jsonResult = JSON.toJSONString(new JsonResult("服务器异常,请联系管理员!", false));
            response.getWriter().write(jsonResult);
        }
    }
}